package com.tang.hawkmusic.activity.local;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.tang.hawkmusic.R;
import com.tang.hawkmusic.fragment.LocalMusicFragment;

public class LocalActivity extends AppCompatActivity {

    private TabLayout localMainTabLayout;
    private ViewPager2 localMainViewPager;
    private LocalViewModel localViewModel;
    private ImageView backBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local);
        localViewModel=new ViewModelProvider(this).get(LocalViewModel.class);
        localViewModel.initFragments();
        initView();
        getGranted();
        localViewModel.initMusicList();
        LocalMusicFragment localMusicFragment= (LocalMusicFragment) localViewModel.getFragments().get(0);
        localMusicFragment.setMusics(localViewModel.getMusics());

    }
    public void initView(){
        localMainTabLayout=findViewById(R.id.local_main_tablayout);
        localMainViewPager=findViewById(R.id.local_main_ViewPager);
        localMainViewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return localViewModel.getFragments().get(position);
            }

            @Override
            public int getItemCount() {
                return localViewModel.getFragments().size();
            }
        });
        new TabLayoutMediator(localMainTabLayout, localMainViewPager, (tab, position) -> {
            switch (position){
                case 0:tab.setText("单曲");break;
                case 1:tab.setText("声音");break;
                case 2:tab.setText("MV");break;
            }

        }).attach();

        backBtn=findViewById(R.id.local_back_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void getGranted(){
        if (ContextCompat.checkSelfPermission(LocalActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(LocalActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }
    }

}